import { authMiddleware } from '@/lib/api';
import { clientQueryPostDetails, queryPath } from '@/services/api';
import { cookies } from 'next/headers';
import PostIdPage from '@/app/[locale]/posts/[id]/postid';
import ResetPage from '@/app/[locale]/reset/reset';
import type { Metadata as MetadataNext } from 'next';
import type { IPath, IPostClientDetails } from '@/interfaces';
import { createError, getMetadata, isNum } from '@/lib/tool';
import { notFound } from 'next/navigation';
import { getTranslator } from 'next-intl/server';
import { getTranslatedFields } from '@/lib/dictionaries';

async function getData(id: string) {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = clientQueryPostDetails({
      baseURL: process.env.APP_API_SERVER,
      token,
      id,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    return {
      isSuccess: true,
      isError: false,
      data: {
        path: resp1.data as IPath,
        postDetails: resp2.data as IPostClientDetails,
      },
    };
  } catch (e: any) {
    return {
      isSuccess: false,
      isError: true,
      error: e,
    };
  }
}

export async function generateMetadata({
  params: { id, locale },
  searchParams = {},
}: {
  params: { id?: string; locale: string };
  searchParams: {};
}): Promise<MetadataNext> {
  if (!id || !isNum(id)) {
    notFound();
  }

  const t = await getTranslator(locale);
  const data = await getData(id);
  if (data.isError) {
    return getMetadata({ title: t('postIdPage.articleDetails') });
  }

  const { postDetails } = data.data!;
  const basic = postDetails.basic;

  return getMetadata({
    title: basic.name,
    authors: {
      url: `/users/${basic.createdBy}`,
      name: basic.creatorAlias,
    },
    creator: `${basic.creatorAlias}(ID. ${basic.createdBy})`,
    description: basic.overview
      ? `${basic.overview} - ${
          basic.customTags.map((tag: string) => `#${tag}`).join(', ') || ''
        }`
      : '',
  });
}

export default async function Page({
  params: { id, locale },
  searchParams: { v },
}: {
  params: { id?: string; locale: string };
  searchParams: { v?: 'h5' };
}) {
  if (!id || !isNum(id)) {
    notFound();
  }

  const data = await getData(id);
  if (data.isError) {
    return <ResetPage error={createError(data.error)} />;
  }

  const source = data.data!;
  const translatedFields = await getTranslatedFields(locale, 'postIdPage');

  return (
    <PostIdPage
      source={source}
      translatedFields={translatedFields}
      queryKey={[]}
    />
  );
}
